﻿// See https://aka.ms/new-console-template for more information
using Autofac;
using Autofac_Ioc;
using System.ComponentModel;

Console.WriteLine("Hello, World!");

ContainerBuilder containerBuilder = new ContainerBuilder();

//注册类,每次取出来都是新的实例
containerBuilder.RegisterType<Student>();

//注册单例类
//containerBuilder.RegisterInstance(new Student());

//基于接口注册
//containerBuilder.RegisterType<Student>().As<IPerson>();
//同一接口注册多个类，后面的会覆盖前面的，也可以通过 PreserveExistingDefaults 设置为非默认
//containerBuilder.RegisterType<WoMan>().As<IPerson>().PreserveExistingDefaults();

//单接口多实现,通过Named制定名称
//containerBuilder.RegisterType<Student>().Named<IPerson>("Student");
//containerBuilder.RegisterType<WoMan>().Named<IPerson>("WoMan");

containerBuilder.RegisterType<Student>().Keyed<IPerson>(PersonType.Student);
containerBuilder.RegisterType<WoMan>().Keyed<IPerson>(PersonType.WoMan)
                .OnRegistered(e => Console.WriteLine("在注册的时候调用!"))
                .OnPreparing(e => Console.WriteLine("在准备创建的时候调用!"))
                .OnActivating(e => Console.WriteLine("在创建之前调用!"))
                .OnActivated(e => Console.WriteLine("创建之后调用!"))
                .OnRelease(e => Console.WriteLine("在释放占用的资源之前调用!")); ;


Autofac.IContainer container = containerBuilder.Build();

Student student = container.Resolve<Student>();
student.Name = "李四";
Console.WriteLine(student.GetName());
Student student1 = container.Resolve<Student>();
Console.WriteLine(student1.GetName());


//Console.WriteLine("=============基于接口注册=============");
//IPerson person = container.Resolve<IPerson>();
//Console.WriteLine(person.GetName());


//Console.WriteLine("=============单接口多实现=============");
//IPerson person = container.ResolveNamed<IPerson>("Student");
//Console.WriteLine(person.GetName());
//IPerson person1 = container.ResolveNamed<IPerson>("WoMan");
//Console.WriteLine(person1.GetName());

IPerson person = container.ResolveKeyed<IPerson>(PersonType.Student);
Console.WriteLine(person.GetName());
IPerson person1 = container.ResolveKeyed<IPerson>(PersonType.WoMan);
Console.WriteLine(person1.GetName());

Console.ReadKey();


